package com.jgame.secondarymarket.domain.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jgame.secondarymarket.domain.product.entity.Product;
import com.jgame.secondarymarket.domain.product.entity.ProductProperties;
import com.jgame.secondarymarket.domain.product.entity.Specification;
import com.jgame.secondarymarket.domain.product.repository.ProductPropertiesRepository;
import com.jgame.secondarymarket.domain.product.repository.ProductRepository;
import com.jgame.secondarymarket.domain.product.repository.SpecificationRepository;
import com.jgame.secondarymarket.domain.product.service.PropertiesService;
import com.jgame.secondarymarket.infrastructure.excetpions.BussnessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @title: PropertiesServiceImpl
 * @Author Wangsj
 * @Date: 2021/7/23
 */
@Service
public class PropertiesServiceImpl implements PropertiesService {
    @Autowired
    ProductRepository productRepository;
    @Autowired
    SpecificationRepository specificationRepository;
    @Autowired
    ProductPropertiesRepository productPropertiesRepository;

    @Override
    public void delById(Long productId, List<Long> propertiesIds) {
        Product product = productRepository.getProductOrThrow(productId);

        //查询该属性下的规格，若存在则不能删除
        List<Specification> specifications = specificationRepository.listByProductIdAndPropertiesIds(product.getId(), propertiesIds);
        if (CollectionUtil.isNotEmpty(specifications)) {
            throw BussnessException.throwException("仍有该属性的规格未删除！！");
        }
        //执行删除
        productPropertiesRepository.deletByIds(product.getId(), propertiesIds);
    }

    @Override
    public void add(Long productId, List<ProductProperties> properties) {
        Product product = productRepository.getProductOrThrow(productId);
        properties.stream().forEach(p -> {
            p.setProductId(product.getId());
        });

        productPropertiesRepository.saveBatch(properties);
    }

}
